package com.poker.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.poker.base.MyRealm;
import com.poker.base.Result;
import com.poker.base.ResultCode;
import com.poker.dao.LoginLogMapper;
import com.poker.dao.PlayerMapper;
import com.poker.dao.UserMapper;
import com.poker.entity.LoginLog;
import com.poker.entity.Player;
import com.poker.entity.User;
import com.poker.service.UserService;
import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.UserAgent;
import eu.bitwalker.useragentutils.Version;
import io.swagger.models.properties.UUIDProperty;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.IdGenerator;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private LoginLogMapper loginLogMapper;
    @Autowired
    private PlayerMapper playerMapper;

    @Override
    public User getOneUser(String userId) {
        User user = userMapper.selectById(userId);
        user.setIcon(new String(user.getPhoto()));
        return user;
    }

    @Override
    public Result<User> login(String userId, String password, HttpServletRequest request) throws UnknownHostException {
        User queryObj = new User();
        queryObj.setUserId(userId);
        queryObj.setPassword(password);
        User currUser = userMapper.selectOne(new QueryWrapper<>(queryObj));
        if (null == currUser) {
            return Result.error(ResultCode.NORMAL_ERROR,"用户名或密码错误");
        }else{
            //记录一次登录记录
            LoginLog ll = new LoginLog();
            ll.setUserId(userId);
            ll.setLoginTime(new Date());
            //获取浏览器信息
            Browser browser = UserAgent.parseUserAgentString(request.getHeader("User-Agent")).getBrowser();
            Version version = browser.getVersion(request.getHeader("User-Agent"));
            ll.setBrowser(browser.getName() +"/"+version.getVersion());
            InetAddress ip4 = Inet4Address.getLocalHost();
            System.out.println(ip4.getHostAddress());
            ll.setIp(ip4.getHostAddress());
            loginLogMapper.insert(ll);
            //shiro的登录
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(userId,password,false);
            subject.login(token);
            System.out.println("当前用户是否登陆"+subject.isAuthenticated());
            Session session = subject.getSession();
            session.setAttribute("user",currUser);
            //设置登录的有效时长为600min
            session.setTimeout(60*1000*600);
            currUser.setIcon(new String(currUser.getPhoto()));
            return Result.success(currUser,"登录成功");
        }
    }

    @Override
    public IPage<LoginLog> getLoginLog(IPage<LoginLog> pageReq) {
        String userId = MyRealm.getUserId();
//        if (null == MyRealm.getUserId()){
//            userId = "sushipei";
//        }
        QueryWrapper<LoginLog> queryWrapper = new QueryWrapper<LoginLog>().eq("USER_ID", userId).orderByDesc("LOGIN_TIME");
        return loginLogMapper.selectPage(pageReq, queryWrapper);
    }

    @Override
    public Result<String> delLog(String id) {
        loginLogMapper.deleteById(id);
        return Result.success("删除成功");
    }

    @Override
    public Result<String> logout() {
        //删除选座的全部数据记录
        playerMapper.delete(null);
        //playerMapper.delete(new QueryWrapper<Player>().lambda().eq(Player::getUserId,MyRealm.getUserId()));
        //销毁session
        SecurityUtils.getSubject().logout();
        return Result.success("已安全退出登录");
    }
}
